﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace Simhopp.Model
{
    class Listener : InterfaceListenerModel
    {
        public Socket socket { get; set; }

        public bool Listening { get; private set; }
        public int Port { get; private set; }

        public bool isJudge { get; set; }

        public Listener(int port)
        {
            Port = port;
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        public void Start()
        {
            string DnsInfo;
            if (Listening)
                return;

            if (isJudge)
                DnsInfo = "";
            else
                DnsInfo = "www.fruitcakeserver.com";

            IPHostEntry ipHostInfo = Dns.GetHostEntry(DnsInfo);
            IPAddress ipAddress = ipHostInfo.AddressList.First(a => a.AddressFamily == AddressFamily.InterNetwork);
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, 888);

            socket.Bind(remoteEP);
            //socket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), Port));
            socket.Listen(0);

            socket.BeginAccept(callback, null);
            Listening = true;
        }

        public void Stop()
        {
            if (!Listening)
                return;

            socket.Close();
            socket.Dispose();
            Listening = false;
            //socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        public void callback(IAsyncResult ar)
        {
            try
            {

                Socket s = this.socket.EndAccept(ar);

                if (SocketAccepted != null)
                {
                    SocketAccepted(s);
                }

                this.socket.BeginAccept(callback, null);


            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Message);
            }
        }

        public delegate void SocketAcceptedHandler(Socket e);
        public event SocketAcceptedHandler SocketAccepted;
    }
}
